package cn.iocoder.yudao.module.system.controller.admin.chaoshun;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.enums.CommonSfEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.dict.core.DictFrameworkUtils;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.module.system.controller.admin.chaoshun.vo.sp.ChaoshunspRespVO;
import cn.iocoder.yudao.module.system.controller.admin.chaoshun.vo.sp.SpPageReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.chaoshun.ChaoshunSpDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.chaoshun.ChaoshunSpService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.system.enums.DictTypeConstants.*;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_NOT_EXISTS;

@Tag(name = "管理后台 - 送货人")
@RestController
@RequestMapping("/chaoshun/songhr")
@Validated
public class ChaoshunSonghrController {

    @Resource
    private ChaoshunSpService chaoshunSpService;
    @Resource
    private AdminUserService userService;

    @GetMapping("/page")
    @Operation(summary = "获得商品列表")
    @PreAuthorize("@ss.hasPermission('chaoshun:songhr:query')")
    public CommonResult<PageResult<ChaoshunspRespVO>> getCourierPage(@Valid SpPageReqVO pageReqVO) {
        if (StrUtil.isEmpty(pageReqVO.getSonghr())) {
            // 设置查询条件-用户名
            Long userId = WebFrameworkUtils.getLoginUserId();
            // 获得用户
            AdminUserDO user = userService.getUser(userId);
            if (user == null) {
                throw exception(USER_NOT_EXISTS);
            }
            pageReqVO.setSonghr(user.getUsername());
        }
        // 设置查询条件-送货时间
        String apshsjSj = pageReqVO.getApshsjSj();
        if ("1".equals(apshsjSj)) {
            // 获取今天的日期
            LocalDate today = LocalDate.now();
            // 创建今天的零点时间
            LocalDateTime todayMidnight = today.atTime(LocalTime.MIDNIGHT);
            // 获取明天的日期
            LocalDate tomorrow = today.plusDays(1);
            // 创建明天的零点时间
            LocalDateTime tomorrowMidnight = tomorrow.atTime(LocalTime.MIDNIGHT);
            pageReqVO.setApshsj(new LocalDateTime[]{todayMidnight, tomorrowMidnight});
        } else if ("2".equals(apshsjSj)) {
            // 获取今天的日期
            LocalDate today = LocalDate.now();
            // 创建今天的零点时间
            LocalDateTime todayMidnight = today.atTime(LocalTime.MIDNIGHT);
            // 获取昨天的日期
            LocalDate tomorrow = today.minusDays(1);
            // 创建昨天的零点时间
            LocalDateTime yesterdayMidnight = tomorrow.atTime(LocalTime.MIDNIGHT);
            pageReqVO.setApshsj(new LocalDateTime[]{yesterdayMidnight, todayMidnight});
        } else if ("3".equals(apshsjSj)) {
            // 获取当前日期时间
            LocalDateTime now = LocalDateTime.now();

            // 获取本周周一的零点时间
            LocalDateTime mondayThisWeek = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).with(LocalTime.MIDNIGHT);

            // 获取下周一的零点时间（即在本周周一的基础上加一周）
            LocalDateTime mondayNextWeek = mondayThisWeek.plus(1, ChronoUnit.WEEKS);
            pageReqVO.setApshsj(new LocalDateTime[]{mondayThisWeek, mondayNextWeek});
        } else if ("4".equals(apshsjSj)) {
            // 获取当前日期
            LocalDate today = LocalDate.now();

            // 获取当前月份的第一天
            LocalDate firstDayOfMonth = today.withDayOfMonth(1);

            // 转换为当天的零点时间
            LocalDateTime startOfMonth = firstDayOfMonth.atStartOfDay();

            // 获取下个月的第一天（下个月的第一天在当前月份的基础上加一个月）
            LocalDate firstDayOfNextMonth = today.withDayOfMonth(1).plusMonths(1);

            // 转换为当天的零点时间
            LocalDateTime startOfNextMonth = firstDayOfNextMonth.atStartOfDay();
            pageReqVO.setApshsj(new LocalDateTime[]{startOfMonth, startOfNextMonth});
        }
        // 获得商品信息分页列表
        PageResult<ChaoshunSpDO> pageResult = chaoshunSpService.getSpPage(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(new PageResult<>(pageResult.getTotal()));
        }
        // 拼接数据
        return success(new PageResult<>(CollectionUtils.convertList(pageResult.getList(), sp -> {
            ChaoshunspRespVO respVO = BeanUtil.copyProperties(sp, ChaoshunspRespVO.class);
            Integer yccs = respVO.getYccs();
            if (yccs > 0) {
                respVO.setTz(" 延" + yccs);
            }
            if (CommonSfEnum.isEnable(respVO.getSffh())) {
                respVO.setTz(StrUtil.trimToEmpty(respVO.getTz()) + " 返");
            }
            if (CommonSfEnum.isEnable(respVO.getSfbl())) {
                respVO.setTz(StrUtil.trimToEmpty(respVO.getTz()) + " 补");
            }
            respVO.setYffsmc(DictFrameworkUtils.getDictDataLabel(COMMON_YFZFFS, sp.getYffs()));
            respVO.setHkfsmc(DictFrameworkUtils.getDictDataLabel(COMMON_HKZFFS, sp.getHkfs()));
            respVO.setSfsmmc(DictFrameworkUtils.getDictDataLabel(COMMON_SF, sp.getSfsm()));
            return respVO;
        }),
        pageResult.getTotal()));
    }


}
